<!--
 * @Author: your name
 * @Date: 2021-08-02 01:29:27
 * @LastEditTime: 2021-09-01 11:12:28
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \aircityinit\src\components\player\player.vue
-->
<template>
  <div ref="player" id="player"></div>
</template>
<script>
import OnEvent from "@/AirCityUtils/Event";
import OnReady from "@/AirCityUtils/onReady";
import { mapState, mapMutations } from "vuex";
import {
  getMatchServer,
  ManageCommand,
  CommandType,
  ManageResult,
} from "./connect";
export default {
  data() {
    return {
      __ws: null,
      __authorization: null,
      Version: null,
    };
  },
  computed: {
    // 获取AirCity模块里的状态
    ...mapState("AirCity", ["AirCityApi", "AirCityPlayer"]),
  },
  watch: {},
  methods: {
    ...mapMutations({
      //同步Mutation
      setAirCityApi_mut: "AirCity/setAirCityApi_mut",
      setAirCityPlayer_mut: "AirCity/setAirCityPlayer_mut",
    }),
    // ...mapActions({
    //     //异步action
    //     setAirCityApi_act: 'AirCity/etAirCityApi_act',
    //     setAirCityPlayer_act: 'AirCity/setAirCityPlayer_act',
    // }),
    connect() {
      let connectInfo = getMatchServer();
      this.__ws = new WebSocket(connectInfo.url);
      this.__ws.onopen = () => {
        // this.info.__bConnected = true;
        console.log("已连接WebSocket!");
        if (connectInfo.Version === 4.3) {
          console.log("4.3版本");
          this.Version = 4.3;
          // 4.3版本无需登录即可进行实例管理
          this.sendData({
            command: CommandType.GetOneFreeInstanceRunning,
          });
        } else if (connectInfo.Version === 5.0) {
          this.Version = 5.0;

          console.log("5.0版本");

          // 5.0版本需登录才可进行实例管理
          // 连接成功时进行登录
          this.sendData({
            command: ManageCommand.Login,
            userName: userInfo ? userInfo.UserName : "admin",
            password: userInfo ? userInfo.PassWord : "admin",
          });
        }
      };
      this.__ws.onmessage = (event) => {
        let o = JSON.parse(event.data);
        console.log(o,'2009');

        //检查登录是否过期
        if (o.result == 1 && this.Version === 5.0) {
          this.$message("登录失败或者登录信息已过期，请重新登录！");
          return;
        }
        switch (o.command) {
          case -1:
            {
              if (o.result == 0) {
                this.__authorization = o.authorization; //保存
                this.$message.success("登录成功");

                this.sendData({
                  command: ManageCommand.GetOneFreeInstanceRunning,
                  details: true,
                  connections: true,
                });
              }
            }
            break;
          case 1:
            break;
          case 6:
            /**
             * @4.3版本的实例连接:
             * @param {instanceId}
             * @return {initInterface_4()}
             */
            this.initInterface_4(true, true, o.instanceId);
            window.addEventListener("resize", this.onResize);
            window.addEventListener(
              "beforeunload",
              this.beforeunloadHandler,
              false
            );
            break;
          case 100:
            break;
          case 103:
            /**
             * @5.0版本的实例连接:
             * @param {id}
             * @return {initInterface()}
             */

            // 这里的返回是获取到空闲实例（或者正在运行的实例）
            // 在这里进行实例的连接
            this.initInterface_5(true, o.id);
            window.addEventListener("resize", this.onResize);
            window.addEventListener(
              "beforeunload",
              this.beforeunloadHandler,
              false
            );
            break;
        }
      };
      this.__ws.onclose = () => {
        this.__ws = null;
        this.connect();
      };

      this.__ws.onerror = function(event) {
        this.__ws = null;
      };
    },
    // 发送WebSocket指令
    sendData(o) {
      //5.0集群版cloud需要在发送之前需要附加上授权信息以进行权限验证
      if (this.__authorization) {
        o.authorization = this.__authorization;
      }
      this.__ws.send(JSON.stringify(o));
    },
    // 5.0连接实例
    initInterface_5(iscloud, IID) {
      let log = () => {};
      //onReady
      let _onReady = () => {
        OnReady();
      };
      //onEvent
      let _onEvent = (e) => {
        OnEvent(e);
      };
      let _onClose = (e) => {
        console.log(e);
        //如果没有指定工程文件，则加上pid参数，pid=-1让服务器随便指定一个工程文件
        //如果想访问指定的工程文件，则明确指定pid, 例如pid=3
        if (e && e.code == 4009) {
          if (location.href.indexOf("?") == -1) location.href += "?pid=-1";
          else location.href += "&pid=-1";
        }
      };
      // _onApiVersion
      let _onApiVersion = (e) => {
        console.log(e, "_onApiVersion");
      };
      //AirCityAPI初始化选项
      let apiOptions = {
        onReady: _onReady,
        onApiVersion: _onApiVersion,
        onEvent: _onEvent,
        onLog: log,
        useColorLog: false, //仅用于SDK测试页面，二次开发请设置为false
      };
      //2021.07.30 因为支持了端口映射，所以这个地方要处理一下内外网host的问题
      //因为HostConfig里自动生成的是内网地址，所以这个地方要根据当前访问的地址替换一下
      // if (location.protocol != "file:") {
      //   HostConfig.Player =
      //     location.hostname + ":" + HostConfig.Player.split(":")[1];
      // }
      //Cloud需要同时初始化AirCityAPI和AirCityPlayer
      if (iscloud) {
        //AirCityPlayer
        let options;
        if (document.getElementById("player")) {
          //需要显示视频流
          options = {
            iid: IID, //如果想连接指定的云渲染实例，可以指定这个参数
            pid: null,
            domId: "player",
            apiOptions: apiOptions,
            showMarker: false,
            showStartupInfo: false,
            onclose: _onClose,
          };
        } else {
          options = {
            iid: IID, //不带视频流的连接必须指定云渲染实例
            pid: null,
            apiOptions: apiOptions,
          };
        }
        let aircityPlayer = new AirCityPlayer(HostConfig.Player, options);
        // 提交仓库
        this.setAirCityPlayer_mut(aircityPlayer);
        console.log(aircityPlayer);
        //对于Cloud应用可以不用显式的创建AirCityAPI对象，只需要在AirCityPlayer创建参数里指定apiOptions，就会自动创建。
        let aircityApi = aircityPlayer.getAPI();
        // 提交仓库
        this.setAirCityApi_mut(aircityApi);
      }

      //Explorer只需要初始化AirCityAPI
      else {
        aircityApi = new AirCityAPI(HostConfig.AirCityAPI, apiOptions);
      }
    },
    // 4.3连接实例
    initInterface_4(withPlayer, withApi, instanceId) {
      console.log(instanceId, "instanceId");
      //AirCityPlayer
      if (withPlayer) {
        let options = {
          domId: "player",
          token: window.HostConfig.Token,
          showMarker: false,
          showStartupInfo: false,
        };
        let aircityPlayer = new window.AirCityPlayer(
          instanceId || window.HostConfig.Player,
          options
        );
        // 提交仓库
        this.setAirCityPlayer_mut(aircityPlayer);
      }

      //AirCityAPI
      if (withApi) {
        let aircityApi = new window.AirCityAPI(
          instanceId || window.HostConfig.AirCityAPI,
          {
            onReady: () => {
              //此时可以调用接口了
              OnReady();
            },
            onEvent: (e) => {
              OnEvent(e);
            },
            onLog: this.log,
            useColorLog: false, //仅用于SDK测试页面，二次开发请设置为false
          }
        );
        // 提交仓库
        this.setAirCityApi_mut(aircityApi);
      }
    },
    onResize() {
      let player = document.getElementById("player");
      player.style.height = window.innerHeight + "px";
      player.style.width = window.innerWidth + "px";
    },
    beforeunloadHandler() {
      console.log("页面刷新前");
      window.__g.reset();
    },
  },
  created() {},
  mounted() {
    this.connect();
  },
  beforeCreate() {},
  beforeMount() {},
  beforeUpdate() {},
  updated() {},
  beforeDestroy() {
    console.log("断开实例");
    this.AirCityApi.destroy();
    this.AirCityPlayer.destroy();
    // window.removeEventListener('load', this.onLoad)
    window.removeEventListener("resize", this.onResize);
    window.removeEventListener("beforeunload", this.beforeunloadHandler);
  },
  destroyed() {},
  activated() {},
  components: {},
};
</script>

<style lang="scss" scoped>
#player {
  width: 100%;
  height: 100%;
  position: absolute;
  z-index: 0;
}
</style>
